﻿using SimpleESBCore.Common;
using SimpleESBCore.Implement;
using SimpleESBCore.Implement.Datas;
using SimpleESBCore.Implement.Events;
using SimpleESBCore.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace SimpleESBServer.Handlers
{
    public class DataReceiveHandler : IHandler<EventBase>
    {
        GlobalClass GlobalClass;
        Socket clientSocket;
        ISerialization serialization;
        SendHelper sh = new SendHelper();
        public DataReceiveHandler(GlobalClass globalClass,Socket socket,ISerialization serialization)
        {
            this.GlobalClass = globalClass;
            this.clientSocket = socket;
            this.serialization = serialization;
        }
        public void Handler(EventBase obj)
        {
            var source = obj.EventData as DataSourceBase;
            if (source is CreateTopicData)
            {
                if (!GlobalClass.EventLists.ContainsKey(source.TopicName))
                {
                    GlobalClass.EventLists.Add(source.TopicName, new List<EventBase>());
                }
            }
            else if (source is DeleteTopicData)
            {
                if (GlobalClass.EventLists.ContainsKey(source.TopicName))
                {
                    GlobalClass.EventLists.Remove(source.TopicName);
                }
            }
            else
            {
                if (!GlobalClass.EventLists.ContainsKey(source.TopicName))
                {
                    if (clientSocket.Connected)
                    {
                        ErrorEvent error = new ErrorEvent();
                        ErrorData data = new ErrorData();
                        data.ErrorMessage= string.Format("发布信息错误,Topic{0}不存在!", source.TopicName);
                        error.EventData = data;
                        sh.SendData(clientSocket, error, serialization);
                    }
                }
                else
                {
                    GlobalClass.EventLists[source.TopicName].Add(obj);
                }
            }
        }
    }
}
